package com.wzt.lianfirecontrol.fragment.my;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.activity.ActivityCollecter;
import com.wzt.lianfirecontrol.activity.BaseActivity;
import com.wzt.lianfirecontrol.activity.LoginActivity;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.AppVersionModel;
import com.wzt.lianfirecontrol.bean.recode.user.RoleConstant;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.fragment.BaseFragment;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.DialogUtils;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.PreferencesUtils;
import com.wzt.lianfirecontrol.utils.ToastUtils;
import com.wzt.lianfirecontrol.utils.Utils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

public class SettingFragment extends BaseFragment {

    private BaseActivity activity;
    private Bundle bundle;
    private View itemContentView;

    private LinearLayout ll_push_switch;
    private Switch switch_baojing;
    private Switch switch_yujing;
    private Switch switch_guzhang;
    private Switch switch_jianguan;

    private LinearLayout ll_change_password;
    private LinearLayout ll_version;
    private TextView tv_version;
    private TextView tv_has_version;

    private Button bt_exit_login;

    private static final int APP_UPDATE_WHAT = 0;
    private Dialog updateDialog;
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView){
            bundle = getArguments();
            activity = getMyActivity();
            itemContentView = inflater.inflate(R.layout.f_setting, container, false);
            initView();
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {
        ll_push_switch = itemContentView.findViewById(R.id.ll_push_switch);
        List<String> alias = UserInfoModel.getUserInfo(activity).getRoleAlias();
        // 维保人员和维保管理人员只显示预约维保单
        if (alias.contains(RoleConstant.ROLE_REPAIR_MANAGER) || alias.contains(RoleConstant.ROLE_REPAIR)){
            ll_push_switch.setVisibility(View.GONE);
        }else {
            ll_push_switch.setVisibility(View.VISIBLE);
            switch_baojing = itemContentView.findViewById(R.id.switch_baojing);
            switch_baojing.setChecked("1".equals(PreferencesUtils.getString(activity, ConstData.SWITCH_BAOJING_STATUS, "1")));
            switch_baojing.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean enable) {
                    String str = "1";
                    if (!enable) {
                        str = "0";
                    }
                    PreferencesUtils.putString(activity, ConstData.SWITCH_BAOJING_STATUS, str);
                }
            });
            switch_yujing = itemContentView.findViewById(R.id.switch_yujing);
            switch_yujing.setChecked("1".equals(PreferencesUtils.getString(activity, ConstData.SWITCH_YUJING_STATUS, "1")));
            switch_yujing.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean enable) {
                    String str = "1";
                    if (!enable) {
                        str = "0";
                    }
                    PreferencesUtils.putString(activity, ConstData.SWITCH_YUJING_STATUS, str);
                }
            });
            switch_guzhang = itemContentView.findViewById(R.id.switch_guzhang);
            switch_guzhang.setChecked("1".equals(PreferencesUtils.getString(activity, ConstData.SWITCH_GUZHANG_STATUS, "1")));
            switch_guzhang.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean enable) {
                    String str = "1";
                    if (!enable) {
                        str = "0";
                    }
                    PreferencesUtils.putString(activity, ConstData.SWITCH_GUZHANG_STATUS, str);
                }
            });
            switch_jianguan = itemContentView.findViewById(R.id.switch_jianguan);
            switch_jianguan.setChecked("1".equals(PreferencesUtils.getString(activity, ConstData.SWITCH_JIANGUAN_STATUS, "1")));
            switch_jianguan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean enable) {
                    String str = "1";
                    if (!enable) {
                        str = "0";
                    }
                    PreferencesUtils.putString(activity, ConstData.SWITCH_JIANGUAN_STATUS, str);
                }
            });
        }

        ll_change_password = itemContentView.findViewById(R.id.ll_change_password);
        ll_change_password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 修改密码
                activity.skipToForgetPs("1");
            }
        });

        ll_version = itemContentView.findViewById(R.id.ll_version);
        tv_has_version = itemContentView.findViewById(R.id.tv_has_version);
        tv_version = itemContentView.findViewById(R.id.tv_version);
        tv_version.setText("V"+Utils.getVersionName(activity));
        ll_version.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // checkApp版本更新

            }
        });

        bt_exit_login = itemContentView.findViewById(R.id.bt_exit_login);
        bt_exit_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityCollecter.finishAllActivitys();
                UserInfoModel.clearUserLoginMessage(activity);
                activity.openActivity(LoginActivity.class);
            }
        });

    }

    private void initUpdateHttpHelper(){
        try {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("version", "V" + Utils.getVersionName(activity));
            hashMap.put("terminal", "App");
            HashMap<String, String> url_params = new HashMap<>();
            url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
            InfoListListHttpHelper infoListListHttpHelper = new InfoListListHttpHelper(activity,
                    Url.APP_UPDATE_URL, APP_UPDATE_WHAT, handler, true, url_params);
            infoListListHttpHelper.setParseJsonData(new InfoListParseJsonData());
            infoListListHttpHelper.getHttpRequest(true);
        }catch (Exception e){}
    }


    private class InfoListListHttpHelper extends HttpHelper {

        public InfoListListHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

    protected class InfoListParseJsonData extends ParseJsonData {

        public InfoListParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
            try {
                switch (what) {
                    case APP_UPDATE_WHAT:
                        JSONObject jsonObject = new JSONObject(dataStr);
                        AppVersionModel appVersionModel = JSONUtil.jsonObjectToBean(new JSONObject(jsonObject.getString("appVersion")), AppVersionModel.class);
                        bundle.putSerializable("data", appVersionModel);
                        bundle.putString("upgrade", jsonObject.getString("upgrade"));
                        bundle.putBoolean(REQUEST_OK, true);
                        break;
                }
            }catch (Exception e){}
        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
                if (msg.what == APP_UPDATE_WHAT){
                    tv_has_version.setVisibility(View.GONE);
                    ll_version.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ToastUtils.showToast(activity, "当前已是最新版本");
                        }
                    });
                }
            return;
        }
        switch (msg.what){
            case APP_UPDATE_WHAT:
                String upgrade = bundle.getString("upgrade");
                if ("true".equals(upgrade)) {
                    AppVersionModel appVersionModel = (AppVersionModel) bundle.getSerializable("data");
                    updateDialog = DialogUtils.createAppUpdateDialog(activity, appVersionModel);
                    if ("1".equals(appVersionModel.getForceUpdate())) {
                        DialogUtils.showDialog(updateDialog);
                    }
                    tv_has_version.setVisibility(View.VISIBLE);
                    ll_version.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            DialogUtils.showDialog(updateDialog);
                        }
                    });
                }else {
                    tv_has_version.setVisibility(View.GONE);
                    ll_version.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ToastUtils.showToast(activity, "当前已是最新版本");
                        }
                    });
                }
                break;

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (null == updateDialog || !updateDialog.isShowing()) {
            initUpdateHttpHelper();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DialogUtils.closeDialog(updateDialog);
    }
}
